package com.can.core.shiro;

import com.can.entity.User;
import com.can.mapper.UserMapper;
import com.can.utils.PasswordHelper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description shiro 访问数据库，验证用户信息
 * @Author can
 * @Date 2018/8/28
 * @Version 1.0
 */
public class ShiroUserDBRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 单独定一个集合对象
        List<String> permissions = new ArrayList<String>();
//        permissions.add("user:create");
        permissions.add("*");
        // 查到权限数据，返回授权信息(要包括 上边的permissions)
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 将上边查询到授权信息填充到simpleAuthorizationInfo对象中
        simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // token.getPrincipal() 用户名，token.getCredentials() 密码
        User user = userMapper.selectByAccount(token.getPrincipal().toString());
        if(null == user){
            throw new UnknownAccountException("用户名或者密码不正确");
        }
        return  new SimpleAuthenticationInfo(user,user.getPassword() , PasswordHelper.credentialsSalt(user.getAccount(),user.getSalt()),getName());
    }
}
